package com.mengshu.platform.web.handler;

import com.mengshu.mybatisplus.exceptions.UniqueKeyException;
import com.mengshu.platform.web.resp.R;
import com.mengshu.security.exceptions.ParamsSignException;
import com.mengshu.token.exceptions.PermissionException;
import com.mengshu.token.exceptions.TokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 *     全局异常返回
 * </p>
 *
 * @author ndd
 * @date 2:35 PM 2020/4/2
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(Exception e) {
        log.error("未知异常", e);
        return R.error(-1, "操作失败");
    }

    @ResponseBody
    @ExceptionHandler(TokenException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(TokenException e) {
        log.error(e.getMessage(), e);
        return R.error(-2, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(PermissionException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(PermissionException e) {
        log.error(e.getMessage(), e);
        return R.error(-3, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(ParamsSignException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(ParamsSignException e) {
        log.error(e.getMessage(), e);
        return R.error(-4, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(BindException e) {
        log.error("参数校验未通过", e);
        return R.error(-5, e.getAllErrors().get(0).getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(UniqueKeyException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(UniqueKeyException e) {
        log.error(e.getMessage(), e);
        return R.error(-6, e.getMessage());
    }
}
